package com.jacky.flutter_screen_recording;

import android.content.DialogInterface;

import com.enotary.mobile.screen.FaXinServiceConnection;
import com.enotary.mobile.screen.IFaXinScreenCallback;
import com.jacky.log.Logger;
import com.jacky.JAlertDialog;

import java.util.HashMap;

import io.flutter.plugin.common.MethodChannel;

class RecordServiceConnection extends FaXinServiceConnection {

    private MethodChannel event = null;
    String evidId;
    RecordServiceConnection(MethodChannel c) {
        event = c;
    }

    @Override
    public void rebindService(int allShotSize, int duration, String formatText) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("allShotSize", allShotSize);
        map.put("duration", duration);
        map.put("formatText", formatText);
        send("rebindService", map);
    }

    @Override
    public void onStartRecordingUI(String text) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("text", text);
        map.put("evidId", evidId);
        send("onStartRecordingUI", map);
    }

    @Override
    public void onStopRecordUI(String jsonText) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("text", jsonText);
        map.put("evidId", evidId);
        send("onStopRecordUI", map);
    }

    @Override
    public void onCallbackUI(int code) {
        send("onCallbackUI", code);
    }

    @Override
    public void onTakeShotOkUI(int allShotSize) {
        send("onTakeShotOkUI", allShotSize);
    }

    @Override
    public void onDurationUI(int duration, String formatText) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("duration", duration);
        map.put("formatText", formatText);
        send("onDurationUI", map);
    }

    public static void sendLog(IFaXinScreenCallback callback, Exception e) {
        e.printStackTrace();
        sendLog(callback, e.getMessage());
    }

    public static void sendLog(IFaXinScreenCallback callback, String e) {
        if(callback instanceof RecordServiceConnection) {
            ((RecordServiceConnection) callback).send("sendLog", e);
        } else {
            Logger.w(e);
        }
    }

    private void send(String method, Object object) {
        if(event == null) {
            Logger.e("JavaEventChannel send failure...");
            return;
        }
        event.invokeMethod(method, object);
    }

    public void release() {
        unbindService();
        event = null;
    }

    @Override
    protected void showAlertDialog(String msg, String jsonText, int code) {
        JAlertDialog dialog = new JAlertDialog()
                .setMessage(msg).setTitle("自动完成").setCancelable(false).setOnDismissListener((d) -> {
            this.onStopRecordUI(jsonText);
        }).setSingleBtn("我知道了", (DialogInterface.OnClickListener) null);
        dialog.show(this._activity);
    }
}
